<template>
  <div class="fee-stages-content">
    <!-- 未收款 || 已驳回 -->
    <page-form ref="formRef" :model="feeForm" :rules="rules" layout="vertical" style="padding-bottom: 20px">
      <table-index
        class="insure-card-table"
        :table="tableCompulsory"
        @loadData="loadCompulsoryData"
        :expandedKeys="expandedKeys"
        @expand="expand"
      >
        <template #selectkey="{ record }">
          {{ record.feeName.substring(record.feeName.indexOf('-') + 1, record.feeName.length) }}
        </template>
        <template #remark="{ record }">
          <i-input v-model="record.remark" />
        </template>
        <template #receivableTime="{ record }">
          <i-date-picker v-if="record.feeStatus != 2 && record.feeStatus != 6" v-model="record.receivableTime" format="YYYY-MM-DD" />
          <template v-else>{{ dayjs(record.receivableTime).format('YYYY-MM-DD') }}</template>
        </template>
        <template #expand-icon="{ expanded }">
          <icon-plus-circle style="font-size: 20px; color: #0256ff" v-if="!expanded" />
          <icon-minus-circle style="font-size: 20px; color: #0256ff" v-else />
        </template>
        <template #createNodeName="{ record, rowIndex }">
          <div v-if="rowIndex == tableCompulsory.dataList.length - 1">
            <a-popconfirm
              v-if="[0, 1, 5].includes(tableCompulsory.dataList[rowIndex].feeStatus)"
              popup-container=".scrollbar .main-section"
              content="请确认，是否删除本期订单，删除后将无法恢复"
              ok-text="确认"
              cancel-text="关闭"
              class="operate-btn del"
              @ok="deleteStageFn(record)"
            >
              <div class="operate-btn del"><icon-minus-circle />删除本期</div>
            </a-popconfirm>
            <div class="operate-btn new" @click="addNewStageFn"><icon-plus-circle />添加新期数</div>
          </div>
        </template>
        <template #expand-row="{ record }">
          <div class="expand-title"> <div class="expand-title-line"></div><div class="expand-title-text">每期应收金额明细</div> </div>
          <!-- 已收款 -->
          <template v-if="record.feeStatus == 2">
            <stages-fee-view :feeDetailList="record.feeDetailList" :orderFeeIndex="tableCompulsory.dataList.indexOf(record)" />
          </template>
          <!-- 未收款 已驳回 -->
          <template v-else-if="record.feeStatus == 1 || record.feeStatus == 5">
            <stages-fee-edit :feeDetailList="record.feeDetailList" :orderFeeIndex="tableCompulsory.dataList.indexOf(record)" />
          </template>
          <template v-else-if="record.feeStatus == 0">
            <stages-fee-pane :order="record" :orderFeeIndex="tableCompulsory.dataList.indexOf(record)" />
          </template>
        </template>
        <template #empty>
          <div class="flex empty-custom-fee">
            <div class="empty-custom-fee-content">
              <a-empty description="暂无费用信息" />
              <a-button type="primary" @click="addNewStageFn">
                <template #icon>
                  <icon-plus />
                </template>
                添加期数
              </a-button>
            </div>
          </div>
        </template>
      </table-index>
    </page-form>
    <div class="fee-statistic">
      <fee-statistic />
    </div>
  </div>
</template>
<script setup>
  import dayjs from 'dayjs'
  import { ref, computed, provide, onMounted } from 'vue'
  import { czsOrderFeeDetailAPI, modifyOrderFee } from '@/api/order/czsOrder'
  import { cloneDeep } from 'lodash-es'
  import { useTable } from '@/hooks/table'
  import { Message } from '@arco-design/web-vue'
  import { buildCostInfoParam, getStoreTemplateDetail, compileFeeItemFromTemplate, getOrderFeeRules } from '../order-fee/fee-utils.js'
  import stagesFeeEdit from '../edit-stages-fees/stages-fee-edit.vue'
  import stagesFeeView from '../edit-stages-fees/stages-fee-view.vue'
  import stagesFeePane from '../edit-stages-fees/stages-fee-pane.vue'
  import feeStatistic from '../order-fee/fee-statistic-stages.vue'

  const props = defineProps({
    id: [Number, String],
  })

  // formRef
  const formRef = ref()
  const orderFeeId = +props.id
  // 展开收起的主键
  const feeIndex = ref(-1)

  const feeForm = ref({
    orderFee: [],
  })
  // rules
  const rules = computed(() => {
    let orderFee = feeForm.value.orderFee
    if (orderFee) {
      let rule = {}
      // 应付款日必填
      orderFee.forEach((item, index) => {
        rule[`orderFee.${index}.receivableTime`] = [
          {
            required: true,
            message: '请选择应付款日',
          },
        ]
        rule[`orderFee.${index}.activeTotalAmount`] = [
          {
            validator: (rule, value, callback) => {
              if (value && value <= 0) {
                callback('每期应收金额需大于0')
              }
              callback()
            },
          },
        ]
      })
      return {
        ...rule,
        ...getOrderFeeRules(orderFee),
      }
    } else {
      return {}
    }
  })
  const feeNameId = ref()
  provide('feeForm', feeForm)

  const orderInfo = ref({})
  provide('orderInfo', orderInfo)
  // 展开
  const expandedKeys = ref([])
  expandedKeys.value.push(orderFeeId)
  const expand = (id) => {
    let expandId = +id
    if (expandedKeys.value.indexOf(expandId) == -1) {
      expandedKeys.value.push(expandId)
    } else {
      expandedKeys.value.splice(expandedKeys.value.indexOf(expandId), 1)
    }
  }
  const loadCompulsoryData = () => {
    tableCompulsory.tableLoading = true
    czsOrderFeeDetailAPI({ id: orderFeeId })
      .then((res) => {
        const result = res.result
        // 多期情况
        const orderFeeList = result.czsOrderFeeList
        orderInfo.value = result.orderInfo
        feeNameId.value = orderFeeList[0].feeNameId
        tableCompulsory.dataList = orderFeeList
        // 处理 orderFee
        feeForm.value.orderFee = orderFeeList
      })
      .finally(() => {
        tableCompulsory.tableLoading = false
      })
  }
  // table 配置
  const tableCompulsory = useTable({
    pagination: false,
    bordered: false,
    scroll: {},
    columns: [
      { title: '期数', slotName: 'selectkey', width: 90, fixed: 'left' },
      { title: '应收款日', dataIndex: 'receivableTime', slotName: 'receivableTime', width: 180 },
      { title: '每期应收金额', unit: '元', dataIndex: 'activeTotalAmount', width: 140 },
      { title: '每期实收金额', unit: '元', dataIndex: 'payAmount', width: 140 },
      { title: '费用状态', dataIndex: 'feeStatusName', width: 90 },
      { title: '完成付款时间', dataIndex: 'confirmTime', width: 180 },
      { title: '备注', dataIndex: 'remark', slotName: 'remark', width: 140 },
      { title: '操作', dataIndex: 'createNodeName', fixed: 'right', slotName: 'createNodeName', width: 130 },
    ],
    expandable: {},
  })
  const deleteStageFn = () => {
    let len = tableCompulsory.dataList.length - 1
    tableCompulsory.dataList.splice(len, 1)
  }
  const siteId = computed(() => {
    return orderInfo.value.siteId
  })
  const storeTemplate = ref()
  const priceTemplateId = ref()
  const getStoreTemplate = (cb) => {
    if (storeTemplate.value && priceTemplateId.value) {
      cb()
    } else {
      // 读取订单信息
      getStoreTemplateDetail(siteId.value, 2, (template, templateId) => {
        storeTemplate.value = template
        priceTemplateId.value = templateId
        cb()
      })
    }
  }
  // 添加新分期
  const addNewStageFn = () => {
    feeIndex.value--
    const list = tableCompulsory.dataList
    let feeName = ''
    // 租车费
    if (feeNameId.value == 1) {
      feeName = `租车费-第${list.length + 1}期`
    } else {
      feeName = `续租费-第${list.length + 1}期`
    }
    let newItem = {
      id: Number(feeIndex.value),
      feeType: 1, // 线下费用
      feeName: feeName,
      feeNameId: feeNameId.value,
      activeTotalAmount: 0,
      payAmount: 0,
      readTemplate: true,
      receivableTime: '',
      feeDetailList: [],
      createTime: '-',
      feeStatus: 0,
      feeStatusName: '未收款',
      feeDetailTypeList: ['basicStageFee', 'addServiceFee', 'preferentialFee', 'otherFee'],
    }
    getStoreTemplate(() => {
      newItem.priceTemplateId = priceTemplateId.value
      compileFeeItemFromTemplate(newItem, storeTemplate.value)
      newItem.feeDetailList.forEach((item) => {
        delete item.remarkLabel
      })
      tableCompulsory.dataList.push(newItem)
    })
    expandedKeys.value = [+newItem.id]
  }
  // 对 orderFee 进行二次处理
  const handleOrderFee = (orderFee) => {
    let tempOrderFee = cloneDeep(orderFee)
    tempOrderFee.forEach((feeItem) => {
      let temp = []
      let feeDetailList = feeItem.feeDetailList
      let remark
      feeDetailList.forEach((feeDetailItem) => {
        let tempObj = {
          feeCategory: feeDetailItem.feeCategory,
          type: 1,
          ...feeDetailItem,
        }
        temp.push(tempObj)
        remark = feeDetailItem.remark
      })
      feeItem.remark = remark
      feeItem.feeDetailList = temp
    })
    return tempOrderFee
  }
  // 新增分期车辆租金必填
  const isNewFee = ref(true)
  const submitFn = () => {
    isNewFee.value = true
    if (feeForm.value.orderFee.length > 0) {
      let orderFee = feeForm.value.orderFee
      let czsOrderFeeList = orderFee.map((orderFeeItem) => {
        if (orderFeeItem.feeStatus != 0) {
          // 对 feeDetailList 进行处理，费用为空则改为0
          orderFeeItem.feeDetailList.forEach((item) => {
            if (item.type == 1) {
              if (!item.amount) item.amount = 0
            } else {
              item.childrenList.forEach((childItem) => {
                if (!childItem.amount) childItem.amount = 0
              })
            }
          })
          return orderFeeItem
        } else {
          // 新增的分期
          let newStage = buildCostInfoParam({ orderFee: [orderFeeItem] })
          let newOrderFee = handleOrderFee(newStage.orderFee)
          console.log(newOrderFee, 'newOrderFee')
          newOrderFee.forEach((item) => {
            if (item.feeDetailList && item.feeDetailList.length > 0) {
              let feeDetailList = item.feeDetailList
              if (feeDetailList.some((i) => i.itemName == '车辆租金')) {
                isNewFee.value = true
              } else {
                isNewFee.value = false
              }
            } else {
              isNewFee.value = false
            }
          })
          return {
            ...newOrderFee[0],
            remark: orderFeeItem.remark,
            receivableTime: orderFeeItem.receivableTime,
          }
        }
      })
      if (!isNewFee.value) {
        return Message.error('请填写新增分期车辆租金')
      }
      if (orderFee.some((item) => !item.receivableTime)) {
        return Message.error('请选择应付款日')
      }
      if (orderFee.some((item) => item.activeTotalAmount < 0)) {
        return Message.error('每期应收金额需大于>=0')
      }
      const param = {
        id: orderFeeId,
        czsOrderFeeList: czsOrderFeeList,
      }
      return new Promise((resolve) => {
        modifyOrderFee(param).then((res) => {
          resolve(res.code)
        })
      })
    } else {
      Message.warning('分期账单至少保留一期')
    }
  }

  defineExpose({
    submitFn,
  })

  onMounted(() => {
    // 加载数据
    loadCompulsoryData()
  })
</script>
<style lang="less" scoped>
  .fee-stages-content {
    display: flex;
    min-height: 55vh;
    max-height: 80vh;
    // position: relative;
    .arco-form {
      width: calc(90vw - 400px);
    }
    .fee-statistic {
      position: fixed;
      background-color: #fff;
      min-width: 336px;
      max-height: 80vh;
      overflow: auto;
      margin-right: 30px;
      right: 5vw;
    }
  }
  .operate-btn {
    font-size: 14px;
    height: 32px;
    line-height: 32px;
    white-space: nowrap;
    outline: none;
    cursor: pointer;
    user-select: none;
    padding: 0 5px;
    .arco-icon {
      margin-right: 8px !important;
    }
    &.del {
      color: #ea0000;
    }
    &.new {
      color: #165dff;
    }
  }
  :deep(.arco-card) {
    background-color: inherit;
  }
  .order-fee-item {
    border-radius: 2px;
    padding: 16px;
    margin-bottom: 20px;
    .order-fee-item-header {
      margin-bottom: 8px;
      font-size: 14px;
      color: #1d2129;
      line-height: 22px;
    }
  }
  .cost-button {
    margin-bottom: 80px;
    div {
      display: inline-block;
      float: right;
      background: #1890ff;
      color: #fff;
      font-size: 14px;
      border-radius: 2px;
      padding: 4px 10px;
      margin-bottom: 20px;
      cursor: pointer;
    }
  }
  :deep(.arco-table-expand-btn) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  :deep(.arco-table-expand-btn:hover) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  :deep(.arco-table-td-content:empty::before) {
    content: ' ';
  }

  // 空数据
  .empty-custom-fee {
    margin: 65px 0;
    justify-content: center;
    :deep(.arco-empty) {
      .arco-empty-description {
        color: #d8d8d8;
        font-size: 12px;
      }
      .arco-icon {
        color: #d8d8d8;
      }
    }
  }
  // 样式优化
  .insure-card-table {
    :deep .arco-table-tr-expand {
      .arco-table-td > .arco-table-cell {
        padding: 20px 39px;
      }
      .arco-table-cell-fixed-expand {
        background-color: #fff;
      }
      .arco-table-cell-fixed-expand .arco-table-td-content {
        background-color: #f7f8fa80;
        padding: 16px 19px 0;
        box-sizing: border-box;
        overflow-x: hidden;
      }
    }
  }

  .expand-title {
    display: flex;
    align-items: center;
    .expand-title-line {
      width: 3px;
      height: 16px;
      display: inline-block;
      background: #1890ff;
      margin-right: 8px;
    }
    .expand-title-text {
      font-size: 16px;
      font-weight: 500;
      color: #1d2129;
      line-height: 22px;
    }
  }
</style>
